﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Limilabs.Client.IMAP;
using Limilabs.Mail;
using Limilabs.Mail.Headers;
using Limilabs.Client.SMTP;

namespace Rsa
{
    class GestorEmail
    {
        public const int UNSEEN = 0;
        public const int AGENDA = 1;
        public const int ALLESCOLA = 2;
        public const int ALL = 3;

        private GestorConfigXML Gxml = null;
        private List<Lista> _listaEmail = null;
        private string Username=null;
        private string Password;
        private string ImapServidor;
        private string ImapPorta;
        private string ImapEncrypt;

        private string SmtpServidor;
        private string SmtpPorta;
        private string SmtpEncrypt;

        private int _tipo = 0;

        private string _from = null;
        private string _to = null;
        private string _subject = null;
        private string _body = null;


        public GestorEmail(GestorConfigXML gx)
        {
            Gxml = gx;
            loadConfig();
        }

        private void loadConfig()
        {
            Hashtable hash = Gxml.loadEmail();
            Username = (string)hash["username"];
            Password = (string)hash["password"];
            ImapServidor = (string)hash["imapServidor"];
            ImapPorta = (string)hash["imapPorta"];
            ImapEncrypt = (string)hash["imapEncrypt"];

            SmtpServidor = (string)hash["smtpServidor"];
            SmtpPorta = (string)hash["smtpPorta"];
            SmtpEncrypt = (string)hash["smtpEncrypt"];
        }


        public void sendEmail()
        {
            loadConfig();
            if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password) ||
                string.IsNullOrWhiteSpace(ImapServidor))
                return;

            MailBuilder builder = new MailBuilder();
            builder.From.Add(new MailBox(Username, "Integracao Sistemas"));
            builder.To.Add(new MailBox(To, To));
            builder.Subject = Subject;
            builder.Text = Body;

            IMail email = builder.Create();

            using (Smtp smtp = new Smtp())
            {
                smtp.Connect(SmtpServidor);    // or ConnectSSL for SSL
                smtp.UseBestLogin(Username, Password); // remove if authentication is not needed

                smtp.SendMessage(email);

                smtp.Close();
            }

        }

        public void start(int opcao)
        {

            loadConfig();
            if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password) ||
                string.IsNullOrWhiteSpace(ImapServidor))
                return;       

            ListaEmail = new List<Lista>();

            using (Imap imap = new Imap())
            {
                imap.Connect(ImapServidor);              // Use overloads or ConnectSSL if you need to specify different port or SSL.
                imap.Login(Username, Password);       // You can also use: LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods,
                // or use UseBestLogin method if you want Mail.dll to choose for you.
                imap.SelectInbox();
                // All search methods return list of unique ids of found messages.

                List<long> proc = null;

                if (opcao == 0)
                {
                    proc = imap.Search(Flag.Unseen);           // Simple 'by flag' search.

                }
                else if (opcao == 1)
                {
                    proc = imap.Search(new SimpleImapQuery  // Simple 'by query object' search.
                    {
                        Subject = "agenda",

                    });
                }
                else if (opcao == 2)
                {
                    proc = imap.Search(new SimpleImapQuery  // Simple 'by query object' search.
                    {
                        To = "ipleiria",
                        
                    });

                }
                else if (Tipo == ALL)
                {
                    proc = imap.GetAll();
                }

                foreach (long uid in proc)
                {
                    IMail email = null;
                    try
                    {
                        email = new MailBuilder().CreateFromEml(
                            imap.GetMessageByUID(uid));
                    }
                    catch
                    {
                        continue;
                    }

                    imap.MarkMessageUnseenByUID(uid);

                    bool test = (email.Subject).StartsWith("Please purchase Mail.dll license", System.StringComparison.OrdinalIgnoreCase);
                    if (test) continue;
                    Console.WriteLine(email.Subject);

                    Lista lista = new Lista();

                    lista.Titulo = email.From.ToString();
                    try
                    {
                        lista.Resumo = email.Subject;
                    }
                    catch
                    {
                        lista.Resumo = email.Subject;
                    }
                    lista.Imagem = "../../imagens/mail.png";
                    lista.Data = email.Date.Value;
                    lista.Corpo = "<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'>";
                    lista.Corpo += email.GetBodyAsHtml();
                    
                    ListaEmail.Add(lista);

                }

                imap.Close();
            }
        }

        #region gets e sets
        public string Body
        {
            get { return _body; }
            set { _body = value; }
        }
        public string Subject
        {
            get { return _subject; }
            set { _subject = value; }
        }
        public string To
        {
            get { return _to; }
            set { _to = value; }
        }

        public string From
        {
            get { return _from; }
            set { _from = value; }
        }

        public int Tipo
        {
            get { return _tipo; }
            set { _tipo = value; }
        }

        public List<Lista> ListaEmail
        {
            get { return _listaEmail; }
            set { _listaEmail = value; }
        }
        #endregion

        public IList<MailBox> tmp { get; set; }
    }
}
